package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.mongodb.Sounds;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.List;

@DubboService
public class PeachblossomApiImpl implements PeachblossomApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存语音文件
     * @param sounds
     */
    @Override
    public void save(Sounds sounds) {
        mongoTemplate.save(sounds);
    }

    /**
     * 随机获取一条语音信息
     * @param userId
     * @return
     */
    @Override
    public Sounds randomSound(long userId) {
        TypedAggregation<Sounds> typedAggregation= Aggregation.newAggregation(Sounds.class,
                Aggregation.sample(1),
                Aggregation.match(Criteria.where("userId").ne(userId)));
        AggregationResults<Sounds> aggregate = mongoTemplate.aggregate(typedAggregation, Sounds.class);
        List<Sounds> mappedResults = aggregate.getMappedResults();
        if(CollUtil.isEmpty(mappedResults)){
            return null;
        }
        return mappedResults.get(0);
    }
}
